package com.xiao.gulimall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xiao.common.to.MemberPriceTo;
import com.xiao.common.to.SkuFullReductionTo;
import com.xiao.common.to.SkuLadderTo;
import com.xiao.common.to.SpuBoundsTo;
import com.xiao.gulimall.product.config.GuliESConfig;
import com.xiao.gulimall.product.dao.*;
import com.xiao.gulimall.product.entity.*;
import com.xiao.gulimall.product.feign.CouponFeignService;
import com.xiao.gulimall.product.service.*;
import com.xiao.gulimall.product.vo.*;
import org.apache.lucene.index.IndexReader;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.common.utils.PageUtils;
import com.xiao.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    SpuInfoDescDao spuInfoDescDao;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrDao attrDao;
    @Autowired
    SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;

    //发布商品的添加
    @Transactional
    @Override
    public void spuSave(SpuVo spuVo) {
        //1.总共11张表！
        //2.1 先保存spu的基本信息 pms_spu_info
        //属性复制spuVo --> SpuInfoEntity
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        //2.2 保存spu的 图片信息 pms_spu_images
        Long spuId = spuInfoEntity.getId();

        if(spuVo.getImages()!=null && spuVo.getImages().size()>0){
            List<SpuImagesEntity> imagesEntityList = spuVo.getImages().stream().map(img -> {
                SpuImagesEntity imagesEntity = new SpuImagesEntity();
                imagesEntity.setSpuId(spuId);
                imagesEntity.setImgUrl(img);
                return imagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(imagesEntityList);
        }
        //2.3 保存spu的 商品介绍图集 pms_spu_info_desc
        List<String> decript = spuVo.getDecript();

        if(decript!=null && decript.size()>0){
            String imgs = "";
            for(String s : decript)
                imgs +=","+s;
            imgs = imgs.substring(1);
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);
            spuInfoDescEntity.setDecript(imgs);
            spuInfoDescDao.insert(spuInfoDescEntity);
        }


        //2.4 保存前台选中的规格参数信息 pms_product_attr_value
        //批量添加  ProductAttrValueEntity  规格参数
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        if(baseAttrs !=null && baseAttrs.size()>0){
            List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuId);
                productAttrValueEntity.setAttrId(attr.getAttrId());
                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
                productAttrValueEntity.setAttrSort(0);
                productAttrValueEntity.setQuickShow(attr.getShowDesc());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(attrValueEntities);
        }
        //得到前台的table信息
        List<Skus> skus = spuVo.getSkus();
        //3.1 保存sku信息  pms_sku_info sku的基本信息
        for(Skus sku : skus){
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setSkuName(sku.getSkuName());
            skuInfoEntity.setSkuDesc(sku.getSkuSubtitle());
            skuInfoEntity.setCatalogId(spuVo.getCatalogId());
            skuInfoEntity.setBrandId(spuVo.getBrandId());

            List<Images> images = sku.getImages();
            Images images1 = null;
            if(images!=null && images.size()>0){
                for(Images img : images){
                    if(img.getDefaultImg().equals(1)){
                        images1 = img;
                        break;
                    }
                }
                skuInfoEntity.setSkuDefaultImg(images1.getImgUrl());
            }
            skuInfoEntity.setSkuTitle(sku.getSkuTitle());
            skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
            skuInfoEntity.setPrice(sku.getPrice());
            skuInfoEntity.setSaleCount(0l);
            //循环添加每一个sku
            skuInfoDao.insert(skuInfoEntity);
            //3.3 保存sku 的图片信息 pms_sku_images
            if(images!=null && images.size()>0){
                List<SkuImagesEntity> skuImagesEntities = images.stream().filter(item ->{
                    return item.getImgUrl()!=null && item.getImgUrl().length()>0;
                }).map(item -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setDefaultImg(item.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setImgUrl(item.getImgUrl());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
            }
            //3.2 保存sku的销售属性 sku_sale_attr_value
            //每个sku的销售属性集合
            List<Attr> attrs = sku.getAttr();
            if(attrs!=null && attrs.size()>0){
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                    skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            }

            //4.1 优惠券系统  sms_sku_full_reduction（每个sku满减）
            SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            skuFullReductionTo.setFullPrice(sku.getFullPrice());
            skuFullReductionTo.setReducePrice(sku.getReducePrice());
            skuFullReductionTo.setAddOther(sku.getPriceStatus());
            couponFeignService.save(skuFullReductionTo);
            //4.2 sms_sku_ladder(每个sku的打折信息)

            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            skuLadderTo.setFullCount(sku.getFullCount());
            skuLadderTo.setDiscount(sku.getDiscount());
            skuLadderTo.setAddOther(sku.getCountStatus());
            couponFeignService.saveSkuLadder(skuLadderTo);
            //买当前商品可以获取的最低积分和金币
            //TODO feign调用
            //4.3 sms_spu_bounds（积分表）
            Bounds bounds = spuVo.getBounds();
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            BeanUtils.copyProperties(bounds,spuBoundsTo);
            spuBoundsTo.setSpuId(spuId);

            couponFeignService.saveSpuBounds(spuBoundsTo);
            //4.4 sms_member_price(会员价格表)
            List<MemberPrice> memberPrice = sku.getMemberPrice();
            if(memberPrice!=null && memberPrice.size()>0){
                List<MemberPriceTo> memberPriceTos = memberPrice.stream().map(member -> {
                    MemberPriceTo memberPriceTo = new MemberPriceTo();
                    memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                    memberPriceTo.setMemberLevelId(member.getId());
                    memberPriceTo.setMemberLevelName(member.getName());
                    memberPriceTo.setMemberPrice(member.getPrice());
                    return memberPriceTo;
                }).collect(Collectors.toList());
                couponFeignService.saveMemberPrices(memberPriceTos);
            }
            //sku添加结束
        }
    }
    @Autowired
    BrandDao brandDao;

    @Autowired
    CategoryDao categoryDao;
    @Autowired
    SkuSaleAttrValueDao skuSaleAttrValueDao;

    @Autowired
    RestHighLevelClient client;
    /**
     * 通过es 上架商品
     * @param id
     */
    @Override
    public void toes(Integer id) {
        List<SkuInfoEntity> entityList = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", id));

        BulkRequest bulkRequest = new BulkRequest();

        for (SkuInfoEntity sku : entityList) {
            ProduceEsVO produceEsVO = new ProduceEsVO();
            BeanUtils.copyProperties(sku,produceEsVO);
            BrandEntity brandEntity = brandDao.selectById(sku.getBrandId());
            produceEsVO.setBrandName(brandEntity.getName());
            produceEsVO.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryDao.selectById(sku.getCatalogId());
            produceEsVO.setCatalogName(categoryEntity.getName());
            List<SkuSaleAttrValueEntity> skuAttrList = skuSaleAttrValueDao.selectList(new QueryWrapper<SkuSaleAttrValueEntity>().eq("sku_id", sku.getSkuId()));
            List<ProduceEsVO.Attrs> attrsList = skuAttrList.stream().map(item -> {
                ProduceEsVO.Attrs attrs = new ProduceEsVO.Attrs();
                BeanUtils.copyProperties(item, attrs);
                return attrs;
            }).collect(Collectors.toList());
            produceEsVO.setAttrs(attrsList);
            produceEsVO.setHasStock(true);
            IndexRequest indexRequest = new IndexRequest("product");
            indexRequest.id(sku.getSkuId().toString());
            String json = JSONObject.toJSONString(produceEsVO);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
            try {
                BulkResponse resp = client.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
                SpuInfoEntity spuInfoEntity = baseMapper.selectById(id);
                spuInfoEntity.setPublishStatus(1);
                baseMapper.updateById(spuInfoEntity);
                System.out.println(resp);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}